<template>
  <page-view class="page-view" :title="false">
    <div slot="headerContent">
      <a-breadcrumb class="s-breadcrumb">
        <a-breadcrumb-item>资产管理</a-breadcrumb-item>
        <a-breadcrumb-item><a @click="goback">物品管理</a></a-breadcrumb-item>
        <a-breadcrumb-item>区域资产历史数据</a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <a-card class="s-card">
      <a-spin :spinning="sending">

        <div class="filter">
          <a-form>
            <a-row>
              <a-col :lg="16" :xs="24">
                <a-col :md="16" :xs="24" style="z-index: 2">
                  <a-form-item label="所属区域" v-bind="formItemLayout">
                    <a-row style="width: 100%" :gutter="12">
                      <a-col :md="12" :xs="24">
                        <a-select v-model="queryParam.area_id" placeholder="请选择区域">
                          <a-select-option
                            v-for="item in areaList"
                            :key="item.id"
                            :value="item.id"
                          >{{ item.name }}</a-select-option>
                        </a-select>
                      </a-col>
                      <a-col :md="12" :xs="24">
                        <a-select
                          v-model="queryParam.area_pid"
                          :disabled="!queryParam.area_id"
                          :placeholder="queryParam.area_id ? '请选择子区域' : '请选择区域'"
                        >
                          <a-select-option
                            v-for="item in childAreaList"
                            :key="item.id"
                            :value="item.id"
                          >{{ item.name }}</a-select-option>
                        </a-select>
                      </a-col>
                    </a-row>
                  </a-form-item>
                </a-col>

                <a-col :md="8" :xs="24" style="z-index: 2">
                  <a-form-item label="物品名称" v-bind="formItemLayout">
                    <a-input v-model="queryParam.goodsName" placeholder="请输入" />
                  </a-form-item>
                </a-col>

                <a-row style="width: 100%; z-index: 1" :gutter="12">
                  <a-col :md="12" :xs="24">
                    <a-form-item label="盘点计划名称" v-bind="formItemLayout" class="label-width-auto">
                      <a-select v-model="queryParam.pid" placeholder="请选择盘点计划">
                        <a-select-option
                          v-for="item in planList"
                          :key="item.id"
                          :value="item.id"
                        >{{ item.name }}</a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                </a-row>
              </a-col>

              <a-col :lg="8" :xs="24">
                <div class="button-container">
                  <a-button type="primary" @click="handleSearch">查询</a-button>
                  <a-button @click="reset">重置</a-button>
                  <a-button @click="handleExport">导出报表</a-button>
                </div>
              </a-col>
            </a-row>
          </a-form>
        </div>

        <s-table
          ref="table"
          class="s-table"
          row-key="index"
          :row-selection="{ onChange }"
          :locale="{ emptyText: '暂无数据' }"
          :show-pagination="false"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: scrollY }"
          :alert="false"
        >
          <template slot="action" slot-scope="item">
            <div class="action-container">
              <span class="success-link" @click="showDetail(item)">详情</span>
            </div>
          </template>
        </s-table>

      </a-spin>
    </a-card>
  </page-view>
</template>

<script>
import { mapState } from 'vuex'
import { PageView, STable } from '@/components'

export default {
  name: 'History',
  components: { PageView, STable },
  inject: ['formItemLayout'],

  // async fetch ({ store, app }) {
  //   const list = []
  //   const { $get } = store
  //   if (!$get(store, 'state.basic.deptList.length')) list.push({ fn: app.$departmentListFunc })
  //   if (!$get(store, 'state.basic.areaList.length')) list.push({ fn: app.$areaListFunc })
  //   await app.$requestList(list)
  //   store.dispatch('basic/setDeptArea')
  // },

  async asyncData ({ $axios, app }) {
    const { $get } = app
    const areaList = await $axios.post('api/area/queryAll', { pid: 0 }).then(res => app.$get(res, 'data.data', [])).catch(e => [])
    const planList = await $axios.post('api/assetsInventoryPlan/query', { pageSize: -1 }).then(res => $get(res, 'data.data.dataList')).catch(e => [])
    return { planList, areaList }
  },

  data () {
    return {
      sending: false,
      scrollY: 400,

      queryParam: { area_pid: undefined, area_id: undefined, goodsName: undefined, pid: undefined },

      columns: [
        { title: '物品编号', width: '10%', align: 'center', dataIndex: 'code' },
        { title: '物品名称', width: '12%', align: 'center', dataIndex: 'goodsName' },
        { title: '所属区域', align: 'center', dataIndex: 'deptName' },
        { title: '上期结存', width: '8%', align: 'center', dataIndex: 'lastBalance' },
        { title: '本期领入', width: '8%', align: 'center', dataIndex: 'receive' },
        { title: '本期减少', width: '8%', align: 'center', dataIndex: 'reduce' },
        { title: '本期结存', width: '8%', align: 'center', dataIndex: 'balance' },
        { title: '操作', width: '100px', align: 'center', scopedSlots: { customRender: 'action' }}
      ],

      rowIds: [],
      rowItems: [],

      childAreaList: []
    }
  },

  computed: {
    ...mapState({
      deptList: state => state.basic.deptList,
      deptListMaps: state => state.basic.deptListMaps
    })
  },

  watch: {
    async 'queryParam.area_id' (pid = -1) {
      this.queryParam.area_pid = undefined
      if (pid === -1) return false
      const { childAreaList, $get, $axios } = this
      childAreaList.splice(0)
      const list = await $axios.post('api/area/queryAll', { pid }).then(res => $get(res, 'data.data', [])).catch(e => [])
      childAreaList.push(...list)
    }
  },

  mounted () {
    if (!process.client) return false
    const viewHeight = document.querySelector('.ant-layout-content').offsetHeight
    this.scrollY = viewHeight - 64 - 55 - 24 * 4 - 97 - 61
    if (this.scrollY < 0) this.scrollY = 600
  },

  methods: {
    async handleExport (index) {
      const { rowIds, rowItems, $message, handleParams } = this
      if (!rowItems.length) {
        $message.destroy()
        $message.error('请选择要导出的报表')
        return false
      }

      this.$toggleSending(1)
      const param = handleParams()
      param.ids = rowItems.map(i => i.id).join(',')
      const fileName = `区域资产历史数据报表_${Date.now()}`
      const bool = await this.$exportFile({ url: 'api/assetsInventory/exportRegionalAssetsList', param, fileName })
      if (bool) {
        rowIds.splice(0)
        rowItems.splice(0)
      }
      this.$toggleSending()
    },

    onChange (ids, items) {
      this.rowIds = ids
      this.rowItems = items
    },

    handleParams () {
      const { queryParam } = this
      const res = {}
      for (const key in queryParam) {
        const item = queryParam[key]
        if (item) res[key] = item
      }
      return res
    },

    loadData () {
      const { handleParams, $axios, $get } = this
      const params = handleParams()
      if (params.deptId) {
        params.areaPid = params.deptId
        delete params.deptId
      }
      const loadRes = { data: [] }

      return $axios.post('api/assetsInventory/regionalAssetsList', params).then(res => {
        loadRes.data = $get(res, 'data.data', []).map((i, index) => Object.assign(i, { index }))
        return loadRes
      }).catch(e => loadRes)
    },

    handleSearch () {
      const { table } = this.$refs
      table && table.refresh && table.refresh()
    },

    reset () {
      this.rowIds.splice(0)
      this.rowItems.splice(0)
      Object.assign(this.queryParam, { area_pid: undefined, area_id: undefined, goodsName: undefined, pid: undefined })
    },

    goback () {
      this.$router.back()
    }
  }
}
</script>

<style lang="less" scoped>
  .filter {
    .button-container {
      text-align: left;

      button {
        margin-bottom: 6px;
      }
    }
  }
</style>
